var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection');
//插入装配关系
exports.createAssemblyRelation = function(assemblyRelation, completeFun) {
    var assemblyRelationEntity = entityCollection.getEntity("AssemblyRelation");
    assemblyRelationEntity.insert(assemblyRelation, function(err, newBarcodeMaster) {
        completeFun(err, newBarcodeMaster);
    });
};
//删除装配关系
exports.deleteById = function(id, completeFun) {
    var assemblyRelationEntity = entityCollection.getEntity("AssemblyRelation");
    assemblyRelationEntity.deleteById(id, function(err, result) {
        completeFun(err, result);
    });
};
//查找条码的所有AssemblyType为2的数据(按时间降序)
exports.findAllByBarcodeMasterAndAssemblyType = function(barcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.find({
        BarcodeMaster: barcodeMaster,
        AssemblyType: 2
    }, {CollectDateTime: -1}, null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配条码信息错误';
            newErr.message = '请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, record);
        }
    });
};

// 根据传入条码ID查找所有历史替换条码，按时间排序
exports.findAssemblyRelations = function (barcodeId) {
    var deferred = Q.defer();

    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({
        $or: [{
            BarcodeMaster: barcodeId,
            AssemblyType: 2
        }, {
            AssemblyBarcode: barcodeId,
            AssemblyType: 2
        }]
    }, null, function (err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询装配关系错误';
            newErr.message = '查询装配关系失败，请检查查询参数！';
            deferred.reject(newErr);
            return;
        }
        if (result === null) {
            deferred.resolve(null);
            return;
        }
        entity.find({ 
            BarcodeMaster: result.BarcodeMaster, 
            AssemblyType: 2 
        }, { 
            CollectDateTime: -1 
        }, {
            path: 'AssemblyBarcode',
            populate: [
                { path: 'ItemMaster', select: 'Code Name Specification ItemCategory' },
                { path: 'MO', select: 'Code LotNumber Customer StartDateTime EndDateTime' }
            ]
        }, function (err, results) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询装配关系错误';
                newErr.message = '查询装配关系失败，请检查查询参数！';
                deferred.reject(newErr);
                return;
            }
            deferred.resolve(results);
        });
    });

    return deferred.promise;
};